extends Control

# 战斗UI控制脚本 - 支持指令和日志面板切换，以及目标选择

# 信号定义，用于与战斗管理器通信
signal attack_pressed
signal skill_pressed
signal defend_pressed
signal item_pressed
signal target_selected(character_node)
signal cancel_target_selection

enum UIType { COMMAND, LOG, TARGET_SELECTION }

# 变量定义
var enemy_target_buttons: Array = []
var current_ui_type: UIType = UIType.COMMAND
var selected_enemy_index: int = -1
var target_indicators: Dictionary = {}

# 节点引用
@onready var command_ui = $CommandUI
@onready var battle_log_container = $BattleLogContainer
@onready var battle_log_label = $BattleLogContainer/BattleLogLabel
@onready var attack_button = $CommandUI/CommandButtons/AttackButton
@onready var skill_button = $CommandUI/CommandButtons/SkillButton
@onready var defend_button = $CommandUI/CommandButtons/DefendButton
@onready var item_button = $CommandUI/CommandButtons/ItemButton
@onready var target_selection_overlay = null


func _ready() -> void:
	# 连接按钮信号
	attack_button.pressed.connect(attack_pressed.emit)
	skill_button.pressed.connect(skill_pressed.emit)
	defend_button.pressed.connect(defend_pressed.emit)
	item_button.pressed.connect(item_pressed.emit)

	# 创建目标选择覆盖层（如果不存在）
	_create_target_selection_overlay()

	# 初始状态：显示命令UI面板（会自动隐藏战斗日志）
	disable_command_ui()
	show_command_ui()


func _create_target_selection_overlay() -> void:
	"""创建目标选择UI覆盖层"""
	if has_node("TargetSelectionOverlay"):
		target_selection_overlay = $TargetSelectionOverlay
	else:
		target_selection_overlay = Control.new()
		target_selection_overlay.name = "TargetSelectionOverlay"
		target_selection_overlay.custom_minimum_size = get_viewport_rect().size
		target_selection_overlay.modulate = Color(1, 1, 1, 0.7)  # 半透明效果
		target_selection_overlay.visible = false
		self.add_child(target_selection_overlay)

		# 添加取消按钮
		var cancel_button = Button.new()
		cancel_button.name = "CancelButton"
		cancel_button.text = "取消"
		cancel_button.position = Vector2(20, 20)
		cancel_button.pressed.connect(cancel_target_selection.emit)
		target_selection_overlay.add_child(cancel_button)

		# 添加提示文本
		var hint_label = Label.new()
		hint_label.name = "HintLabel"
		hint_label.text = "请选择一个目标："
		hint_label.position = Vector2(100, 25)
		target_selection_overlay.add_child(hint_label)


func enable_command_ui() -> void:
	"""启用命令UI"""
	command_ui.visible = true
	attack_button.disabled = false
	skill_button.disabled = false
	defend_button.disabled = false
	item_button.disabled = false


func disable_command_ui() -> void:
	"""禁用命令UI"""
	command_ui.visible = false
	attack_button.disabled = true
	skill_button.disabled = true
	defend_button.disabled = true
	item_button.disabled = true


func show_command_ui() -> void:
	"""显示命令UI面板并自动隐藏战斗日志和目标选择UI"""
	current_ui_type = UIType.COMMAND
	command_ui.visible = true
	battle_log_container.visible = false
	if target_selection_overlay:
		target_selection_overlay.visible = false


func hide_command_ui() -> void:
	"""隐藏命令UI面板"""
	command_ui.visible = false


func show_battle_log() -> void:
	"""显示战斗日志面板并自动隐藏命令UI和目标选择UI"""
	current_ui_type = UIType.LOG
	battle_log_container.visible = true
	command_ui.visible = false
	if target_selection_overlay:
		target_selection_overlay.visible = false


func hide_battle_log() -> void:
	"""隐藏战斗日志面板"""
	battle_log_container.visible = false


func show_target_selection(enemy_nodes: Array) -> void:
	"""显示目标选择UI并隐藏其他UI元素"""
	current_ui_type = UIType.TARGET_SELECTION
	if target_selection_overlay:
		# 隐藏其他UI元素
		command_ui.visible = false
		battle_log_container.visible = false

		# 重置选中状态
		selected_enemy_index = -1
		target_indicators.clear()

		# 更新敌人目标按钮
		_update_enemy_target_buttons(enemy_nodes)

		# 默认选中第一个敌人
		if enemy_target_buttons.size() > 0:
			selected_enemy_index = 0
			_update_selected_indicator()

		# 显示目标选择UI
		target_selection_overlay.visible = true


func hide_target_selection() -> void:
	"""隐藏目标选择UI"""
	if target_selection_overlay:
		target_selection_overlay.visible = false
		# 清理敌人目标按钮
		for button in enemy_target_buttons:
			if button and is_instance_valid(button):
				button.queue_free()
		enemy_target_buttons.clear()

		# 清理目标指示器
		for indicator in target_indicators.values():
			if indicator and is_instance_valid(indicator):
				indicator.queue_free()
		target_indicators.clear()

		# 重置选中状态
		selected_enemy_index = -1


func _update_enemy_target_buttons(enemy_nodes: Array) -> void:
	"""更新敌人目标按钮"""
	# 清理旧按钮
	for button in enemy_target_buttons:
		if button and is_instance_valid(button):
			button.queue_free()
	enemy_target_buttons.clear()

	# 清理旧的目标指示器
	for indicator in target_indicators.values():
		if indicator and is_instance_valid(indicator):
			indicator.queue_free()
	target_indicators.clear()

	if not target_selection_overlay:
		return

	# 创建新按钮和目标指示器
	var button_y = 100
	for enemy_node in enemy_nodes:
		if enemy_node and is_instance_valid(enemy_node):
			var enemy_button = Button.new()
			enemy_button.name = "EnemyTargetButton_" + enemy_node.name
			# 使用节点名称作为敌人名称，简单且可靠
			var enemy_name = enemy_node.name
			enemy_button.text = "攻击: " + enemy_name
			enemy_button.position = Vector2(100, button_y)
			enemy_button.custom_minimum_size = Vector2(200, 40)
			enemy_button.pressed.connect(func(): target_selected.emit(enemy_node))
			target_selection_overlay.add_child(enemy_button)
			enemy_target_buttons.append(enemy_button)
			button_y += 60

			# 为每个敌人节点创建白色的Sprite2D指示器
			_create_target_indicator(enemy_node)


func switch_to_command_mode() -> void:
	"""切换到命令模式：显示命令UI，隐藏战斗日志"""
	show_command_ui()  # 现在会自动隐藏战斗日志
	enable_command_ui()


func switch_to_log_mode() -> void:
	"""切换到日志模式：隐藏命令UI，显示战斗日志"""
	hide_command_ui()  # 现在会自动显示战斗日志
	disable_command_ui()


func _create_target_indicator(enemy_node: Node) -> void:
	"""为敌人节点创建白色的Sprite2D指示器"""
	# 创建白色的Sprite2D
	var indicator = Sprite2D.new()
	indicator.name = "TargetIndicator_{0}".format(enemy_node.name)
	indicator.visible = false

	# 创建纯白色的纹理
	var image = Image.create(10, 10, false, Image.FORMAT_RGBA8)
	image.fill(Color.WHITE)
	var texture = ImageTexture.create_from_image(image)
	indicator.texture = texture

	# 放在敌人节点的左侧
	if enemy_node.has_node("Enemy1Sprite"):
		var enemy_sprite = enemy_node.get_node("Enemy1Sprite")
		if enemy_sprite.is_visible():
			indicator.global_position = (
				enemy_sprite.global_position - Vector2(enemy_sprite.texture.get_width() / 2 + 20, 0)
			)
	elif enemy_node.has_node("Enemy2Sprite"):
		var enemy_sprite = enemy_node.get_node("Enemy2Sprite")
		if enemy_sprite.is_visible():
			indicator.global_position = (
				enemy_sprite.global_position - Vector2(enemy_sprite.texture.get_width() / 2 + 20, 0)
			)
	else:
		# 如果没有精灵节点，就放在敌人节点的位置左侧
		indicator.global_position = enemy_node.global_position - Vector2(30, 0)

	# 将指示器添加到场景根节点（为了确保它在敌人节点之上）
	get_tree().current_scene.add_child(indicator)

	# 存储指示器引用
	target_indicators[enemy_node.get_path()] = indicator


func _update_selected_indicator() -> void:
	"""更新选中的敌人指示器显示状态"""
	# 首先隐藏所有指示器
	for indicator in target_indicators.values():
		if indicator and is_instance_valid(indicator):
			indicator.visible = false

	# 如果有选中的敌人，显示对应的指示器
	if selected_enemy_index >= 0 and selected_enemy_index < enemy_target_buttons.size():
		var selected_button = enemy_target_buttons[selected_enemy_index]
		var enemy_name = selected_button.name.substr(selected_button.name.find("_") + 1)

		# 查找对应的敌人节点
		for enemy_path in target_indicators:
			if str(enemy_path).find(enemy_name) != -1:
				var indicator = target_indicators[enemy_path]
				if indicator and is_instance_valid(indicator):
					indicator.visible = true
				break


func _input(event: InputEvent) -> void:
	"""处理键盘输入，用于选择目标"""
	# 只在目标选择模式下处理输入
	if current_ui_type != UIType.TARGET_SELECTION:
		return

	# 回车键确认选择
	if event is InputEventKey and event.pressed and event.keycode == KEY_ENTER:
		if selected_enemy_index >= 0 and selected_enemy_index < enemy_target_buttons.size():
			var selected_button = enemy_target_buttons[selected_enemy_index]
			var enemy_name = selected_button.name.substr(selected_button.name.find("_") + 1)

			# 查找对应的敌人节点
			for enemy_path in target_indicators:
				if str(enemy_path).find(enemy_name) != -1:
					var enemy_node = get_node_or_null(enemy_path)
					if enemy_node and is_instance_valid(enemy_node):
						target_selected.emit(enemy_node)
						break

	# 上下箭头键切换选中的敌人
	elif event is InputEventKey and event.pressed:
		var previous_index = selected_enemy_index
		if event.keycode == KEY_DOWN and selected_enemy_index < enemy_target_buttons.size() - 1:
			selected_enemy_index += 1
		elif event.keycode == KEY_UP and selected_enemy_index > 0:
			selected_enemy_index -= 1

		# 如果选中的敌人发生了变化，更新指示器
		if previous_index != selected_enemy_index:
			_update_selected_indicator()


func add_battle_log(message: String, color: Color = Color.WHITE) -> void:
	"""添加战斗日志信息"""
	# 在Godot 4.x中，使用append_text和bbcode来添加格式化文本
	var color_hex = color.to_html()
	battle_log_label.append_text("[color={0}]{1}[/color]\n".format([color_hex, message]))
	battle_log_label.scroll_to_line(battle_log_label.get_line_count())
